/**
 * Copyright (C) 2012 The SkyTvOS Project
 * <p/>
 * Version     Date           Author
 * ─────────────────────────────────────
 * 2014年11月13日         Root.Lu
 */

package com.coocaa.x.framework.utils;

import java.util.List;

public class CacheTool<Key, Value> implements ICache<Key, Value> {
    private Cache<Key, Value> cache = new Cache<Key, Value>();
    private ICache<Key, Value> i = null;

    public CacheTool(ICache<Key, Value> i) {
        this.i = i;
    }

    @Override
    public void add(Key key, Value value) {
        // TODO Auto-generated method stub
        synchronized (this) {
            i.add(key, value);
            cache.add(key, value);
        }
    }

    @Override
    public void update(Key key, Value value) {
        // TODO Auto-generated method stub
        synchronized (this) {
            i.update(key, value);
            cache.update(key, value);
        }
    }

    @Override
    public Value get(Key key) {
        // TODO Auto-generated method stub
        synchronized (this) {
            Value ret = cache.get(key);
            if (ret == null)
                ret = i.get(key);
            return ret;
        }
    }

    @Override
    public void remove(Key key) {
        // TODO Auto-generated method stub
        synchronized (this) {
            cache.remove(key);
            i.remove(key);
        }
    }

    @Override
    public List<Key> keys() {
        // TODO Auto-generated method stub
        return cache.keys();
    }

    @Override
    public List<Value> values() {
        // TODO Auto-generated method stub
        return cache.values();
    }

    @Override
    public int size() {
        // TODO Auto-generated method stub
        return cache.size();
    }

    public Key keyAt(int at) {
        return cache.keyAt(at);
    }

    public Value valueAt(int at) {
        return cache.valueAt(at);
    }

    public void flush() {
        // TODO Auto-generated method stub
        synchronized (this) {
            cache.clear();
            List<Key> keys = i.keys();
            for (Key key : keys) {
                Value value = i.get(key);
                if (value != null)
                    cache.add(key, value);
            }
        }
    }

    @Override
    public boolean containsKey(Key key) {
        // TODO Auto-generated method stub
        return cache.containsKey(key);
    }

    @Override
    public boolean containsValue(Value value) {
        // TODO Auto-generated method stub
        return cache.containsValue(value);
    }
}
